package com.lxb.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxb.eduservice.dto.CourseFrontDto;
import com.lxb.eduservice.dto.CourseInfoFormDto;
import com.lxb.eduservice.entity.EduCourse;
import com.lxb.eduservice.entity.EduCourseDescription;
import com.lxb.eduservice.mapper.EduCourseMapper;
import com.lxb.eduservice.service.EduChapterService;
import com.lxb.eduservice.service.EduCourseDescriptionService;
import com.lxb.eduservice.service.EduCourseService;
import com.lxb.eduservice.service.EduVideoService;
import com.lxb.eduservice.vo.course.CoursePublishVo;
import com.lxb.eduservice.vo.front.CourseWebVo;
import com.lxb.servicebase.exceptionhandler.GuliException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 课程业务层
 *
 * @author lixuebin
 * @since 2022-11-06
 */
@Service
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements EduCourseService {

    @Autowired
    private EduCourseDescriptionService descriptionService;
    @Autowired
    private EduChapterService chapterService;
    @Autowired
    private EduVideoService videoService;
    @Autowired
    private EduCourseService courseService;

    @Override
    public String saveCourseInfo(CourseInfoFormDto courseInfoFormDto) {
        EduCourse course = new EduCourse();
        BeanUtils.copyProperties(courseInfoFormDto, course);
        //1.先课程表中添加信息
        int insert = baseMapper.insert(course);
        if (insert <= 0) {
            //添加失败
            throw new GuliException(20001, "添加课程信息失败");
        }

        //获取新生成的课程id
        String courseId = course.getId();

        //2.向课程简介表中添加课程简介
        EduCourseDescription description = new EduCourseDescription();
        //获得课程id
        description.setId(courseId);
        description.setDescription(courseInfoFormDto.getDescription());
        int add = descriptionService.add(description);


        return courseId;
    }

    @Override
    public CourseInfoFormDto getCourseById(String id) {

        CourseInfoFormDto courseInfoFormDto = new CourseInfoFormDto();

        try {
            //根据id查询，课程表
            EduCourse eduCourse = baseMapper.selectById(id);
            BeanUtils.copyProperties(eduCourse, courseInfoFormDto);

            //查询课程简介表
            EduCourseDescription description = descriptionService.getById(id);
            if (description != null) {
                courseInfoFormDto.setDescription(description.getDescription());
            }
        } catch (BeansException e) {
            throw new GuliException(20001, "查询课程信息失败");
        }

        return courseInfoFormDto;
    }

    @Override
    public void updateCourseInfo(CourseInfoFormDto courseInfoFormDto) {

        //修改课程信息
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoFormDto, eduCourse);
        int updateCourse = baseMapper.updateById(eduCourse);

        if (updateCourse == 0) {
            throw new GuliException(20001, "更新课程信息失败");
        }

        //修改课程简介表
        EduCourseDescription description = new EduCourseDescription();
        description.setId(courseInfoFormDto.getId());
        description.setDescription(courseInfoFormDto.getDescription());
        boolean updateById = descriptionService.updateById(description);
        if (!updateById) {
            throw new GuliException(20001, "课程详情信息保存失败");
        }
    }

    /**
     * 根据ID获取课程发布信息
     *
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo getCoursePublishById(String id) {

        return baseMapper.getCoursePublishById(id);
    }

    /**
     * 根据id发布课程
     *
     * @param id
     * @return
     */
    @Override
    public boolean publishCourseById(String id) {
        EduCourse eduCourse = new EduCourse();
        eduCourse.setId(id);
        eduCourse.setStatus("1");
        int i = baseMapper.updateById(eduCourse);
        return i > 0;
    }

    /**
     * 根据id删除课程
     *
     * @param courseId
     */
    @Override
    public void removeCourseById(String courseId) {

        //根据课程id删除小节
        videoService.removeVideoByCourseId(courseId);

        //根据课程id删除章节
        chapterService.removeChapterByCourseId(courseId);

        //根据课程id删除课程简介
        descriptionService.removeDescriptionById(courseId);

        //根据课程id删除课程
        int result = baseMapper.deleteById(courseId);
        if (result == 0) {//删除失败
            throw new GuliException(20001, "删除课程异常");
        }
    }

    /**
     * 根据讲师id，查询教授的课程
     *
     * @param id
     * @return
     */
    @Override
    public List<EduCourse> selectByTeacherID(String id) {

        QueryWrapper<EduCourse> wrapper = new QueryWrapper();
        wrapper.eq("teacher_id", id);
        //按照更新时间，降序
        wrapper.orderByDesc("gmt_modified");
        List<EduCourse> courseList = baseMapper.selectList(wrapper);
        return courseList;
    }

    /**
     * 多条件分页查询课程
     *
     * @param coursePage
     * @param courseFrontDto
     * @return
     */
    @Override
    public Map<String, Object> pageCourse(Page<EduCourse> coursePage, CourseFrontDto courseFrontDto) {

        QueryWrapper<EduCourse> wrapper = new QueryWrapper<>();

        if (courseFrontDto != null) {
            //一级分类
            if (StringUtils.isNotEmpty(courseFrontDto.getSubjectParentId())) {
                wrapper.eq("subject_parent_id", courseFrontDto.getSubjectParentId());
            }
            //二级分类
            if (StringUtils.isNotEmpty(courseFrontDto.getSubjectId())) {
                wrapper.eq("subject_id", courseFrontDto.getSubjectId());
            }
            //销量排序
            if (StringUtils.isNotEmpty(courseFrontDto.getBuyCountSort())) {
                wrapper.orderByDesc("buy_count");
            }
            //最新时间排序
            if (StringUtils.isNotEmpty(courseFrontDto.getGmtCreateSort())) {
                wrapper.orderByDesc("gmt_create");
            }
            //课程销售价格排序
            if (StringUtils.isNotEmpty(courseFrontDto.getPriceSort())) {
                wrapper.orderByDesc("price");
            }
        }

        //调用方法时,底层把分页的全部数据封装到teacherPage对象中
        baseMapper.selectMapsPage(coursePage, wrapper);

        //存放分页数据
        Map<String, Object> map = new HashMap<>();

        List<EduCourse> records = coursePage.getRecords();
        map.put("items", records);//每页数据list集合
        map.put("total", coursePage.getTotal());//总记录数
        map.put("pages", coursePage.getPages());//总页数
        map.put("current", coursePage.getCurrent());//当前页
        map.put("size", coursePage.getSize());//每页记录条数
        map.put("hasNext", coursePage.hasNext());//下一页
        map.put("hasPrevious", coursePage.hasPrevious());//上一页

        return map;
    }

    /**
     * 根据课程id,查询课程信息
     *
     * @param courseId
     * @return
     */
    @Override
    public CourseWebVo getBaseCourseInfo(String courseId) {

        CourseWebVo courseWebVo = baseMapper.selectByCourseIDInfo(courseId);
        return courseWebVo;
    }
}
